package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.entity.SmallPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    //注入service
    @Reference
    private SetmealService setmealService;

    //自动注入jedis
    @Autowired
    private JedisPool jedisPool;

    //上传图片
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        //查看后缀名
        String originalFilename = imgFile.getOriginalFilename();//原始文件名

        //保证不重复，随机生成一个ID，但是需要后缀名
        String fileName = UUID.randomUUID().toString() + originalFilename;

        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //把上传的图片添加到redis中，临时存储起来。用于后期查找垃圾图片，删除
            //jedisPool.getResource().sadd(redis的数据库名,要存储的数据)
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
         return setmealService.findPage(queryPageBean);
    }

    //添加套餐
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkGroupIds){
        //调用service层方法,进行添加
        try {
            setmealService.add(setmeal, checkGroupIds);
        }catch(Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    /**
     * 查询全部的套餐
     * @param smallPageBean
     * @return
     */
    @RequestMapping("/findAll_fxw")
    public PageResult findAll_fxw(@RequestBody SmallPageBean smallPageBean){
        return setmealService.findAll_fxw(smallPageBean);
    }

    @RequestMapping("/findSetmealBySetmealId")
    public PageResult findSetmealBySetmealId(@RequestBody SmallPageBean smallPageBean,String setmealId){
        return setmealService.findAllById(smallPageBean,setmealId);
    }
}
